package per.wsj.httplib.ok.callback;

import com.google.gson.Gson;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import per.wsj.commonlib.net.ParameterizedTypeImpl;
import per.wsj.httplib.ok.base.BaseBean;

public abstract class HttpCallback<T> implements CallBack<T> {

    public void onNext(String responseBody) {
        // 获取包含泛型的父类
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            // 获取父类的泛型
            Type[] types = ((ParameterizedType) type).getActualTypeArguments();
            // 根据泛型构造BaseBean<T>的Type
            Type ty = new ParameterizedTypeImpl(BaseBean.class, new Type[]{types[0]});
            // Gson解析
            BaseBean<T> data = new Gson().fromJson(responseBody, ty);
            onSuccess(data.getData(), "" + data.getErrorCode(), data.getErrorMsg());
        } else {
            throw new ClassCastException();
        }
    }
}